package cn.edu.njnu.opengmpback.Modeling.CallBack;

import cn.edu.njnu.opengmpback.Modeling.socket.ComputeModelSocket;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import org.springframework.web.socket.TextMessage;

/**
 * @Author TRY
 * @Date 2023/4/12 16:02
 * @Version 1.0
 */
public class MyExecStartResultCallback extends ExecStartResultCallback {
    ComputeModelSocket webSocketService;

    private String projectId;

    public MyExecStartResultCallback(String projectId, ComputeModelSocket webSocketService) {
        super(System.out, System.err);
        this.projectId=projectId;
        this.webSocketService=webSocketService;
    }

    @Override
    public void onNext(Frame frame) {
        try {
            if (frame != null) {
                if (frame.getStreamType() == StreamType.STDOUT || frame.getStreamType() == StreamType.STDERR) {
                    String message = new String(frame.getPayload());
                    if (webSocketService != null) {
                        webSocketService.sendMessageByProject(projectId, message);
                    } else {
                        // 打印错误日志或其他处理
                        System.err.println("webSocketService is not initialized.");
                    }
                }
            }else {
                System.out.println("frame is null");
            }
            super.onNext(frame);
        } catch (Exception e) {
            // 捕获所有异常并记录
            e.printStackTrace();
        }
    }
}
